<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  UserOutlined,
  SettingOutlined,
  LogoutOutlined,
  LoginOutlined,
  UserAddOutlined,
  AuditOutlined,
  CloudUploadOutlined,
  DatabaseOutlined,
  BarChartOutlined,
  TeamOutlined,
} from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user'
import type { MenuInfo } from 'ant-design-vue/es/menu/src/interface'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 根据当前路由设置选中的菜单项
const selectedKeys = computed(() => {
  const path = route.path
  if (path === '/') return ['1']
  if (path === '/batch-upload') return ['5']
  if (path === '/spaces') return ['6']
  if (path === '/team-spaces') return ['8']
  if (path === '/analyze') return ['7']
  if (path.includes('/admin')) return ['3']
  if (path.includes('/profile')) return ['4']
  return ['1']
})

// 根据当前路由设置打开的子菜单（暂时未使用，但保留以备将来使用）
// const openKeys = computed(() => {
//   const path = route.path
//   if (path.includes('/admin')) return ['admin']
//   return []
// })

// 处理菜单点击
const handleMenuClick = (event: MenuInfo) => {
  console.log(event.key, typeof event.key)
  switch (event.key) {
    case '1':
      router.push('/')
      break
    case '3':
      if (userStore.isAdmin) {
        router.push('/admin/users')
      }
      break
    case '4':
      router.push('/profile')
      break
    case '5':
      router.push('/batch-upload')
      break
    case '6':
      router.push('/spaces')
      break
    case '7':
      router.push('/analyze')
      break
    case '8':
      router.push('/team-spaces')
      break
  }
}

// 处理用户菜单点击
const handleUserMenuClick = (event: MenuInfo) => {
  const key = event.key
  switch (key) {
    case 'profile':
      router.push('/profile')
      break
    case 'spaces':
      router.push('/spaces')
      break
    case 'team-spaces':
      router.push('/team-spaces')
      break
    case 'analyze':
      router.push('/analyze')
      break
    case 'batch-upload':
      router.push('/batch-upload')
      break
    case 'admin-users':
      router.push('/admin/users')
      break
    case 'admin-pictures-review':
      router.push('/admin/pictures/review')
      break
    case 'admin-pictures-batch-upload':
      router.push('/admin/pictures/batch-upload')
      break
    case 'admin-spaces':
      router.push('/admin/spaces')
      break
    case 'logout':
      handleLogout()
      break
    case 'login':
      router.push('/login')
      break
    case 'register':
      router.push('/register')
      break
  }
}

// 处理登出
const handleLogout = async () => {
  try {
    await userStore.logout()
    await router.push('/')
  } catch (error) {
    console.error('登出失败:', error)
  }
}

// 组件挂载时获取用户信息
onMounted(() => {
  if (!userStore.loginUser) {
    userStore.fetchLoginUser()
  }
})
</script>

<template>
  <a-layout class="layout">
    <a-layout-header class="header">
      <img class="logo" src="@/assets/logo.svg" alt="Han Picture Logo" />
      <div class="nav-content">
        <a-menu
          :selectedKeys="selectedKeys"
          theme="light"
          mode="horizontal"
          :style="{ lineHeight: '64px', border: 'none', background: 'transparent' }"
          @click="handleMenuClick"
        >
          <a-menu-item key="1">首页</a-menu-item>
          <a-menu-item key="6" v-if="userStore.isLogin">我的空间</a-menu-item>
          <a-menu-item key="8" v-if="userStore.isLogin">团队空间</a-menu-item>
          <a-menu-item key="7" v-if="userStore.isLogin">空间分析</a-menu-item>
          <a-menu-item key="5" v-if="userStore.isLogin">批量上传</a-menu-item>
          <a-menu-item key="3" v-if="userStore.isAdmin">系统管理</a-menu-item>
          <a-menu-item key="4" v-if="userStore.isLogin">个人中心</a-menu-item>
        </a-menu>

        <!-- 用户操作区域 -->
        <div class="user-actions">
          <!-- 已登录用户 -->
          <a-dropdown v-if="userStore.isLogin" placement="bottomRight">
            <div class="user-info">
              <a-avatar :size="32" :src="userStore.loginUser?.userAvatar" class="user-avatar">
                {{
                  userStore.loginUser?.userName?.charAt(0) ||
                  userStore.loginUser?.userAccount?.charAt(0)
                }}
              </a-avatar>
              <span class="user-name">
                {{ userStore.loginUser?.userName || userStore.loginUser?.userAccount }}
              </span>
            </div>
            <template #overlay>
              <a-menu @click="handleUserMenuClick">
                <a-menu-item key="profile">
                  <UserOutlined />
                  个人资料
                </a-menu-item>
                <a-menu-item key="spaces">
                  <DatabaseOutlined />
                  我的空间
                </a-menu-item>
                <a-menu-item key="team-spaces">
                  <TeamOutlined />
                  团队空间
                </a-menu-item>
                <a-menu-item key="analyze">
                  <BarChartOutlined />
                  空间分析
                </a-menu-item>
                <a-menu-item key="batch-upload">
                  <CloudUploadOutlined />
                  批量上传
                </a-menu-item>
                <a-sub-menu key="admin" v-if="userStore.isAdmin">
                  <template #title>
                    <SettingOutlined />
                    系统管理
                  </template>
                  <a-menu-item key="admin-users">
                    <UserOutlined />
                    用户管理
                  </a-menu-item>
                  <a-menu-item key="admin-pictures-review">
                    <AuditOutlined />
                    图片审核
                  </a-menu-item>
                  <a-menu-item key="admin-pictures-batch-upload">
                    <CloudUploadOutlined />
                    管理员批量上传
                  </a-menu-item>
                  <a-menu-item key="admin-spaces">
                    <DatabaseOutlined />
                    空间管理
                  </a-menu-item>
                </a-sub-menu>
                <a-menu-divider />
                <a-menu-item key="logout">
                  <LogoutOutlined />
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>

          <!-- 未登录用户 -->
          <a-space v-else>
            <a-button type="text" @click="router.push('/login')">
              <LoginOutlined />
              登录
            </a-button>
            <a-button type="primary" ghost @click="router.push('/register')" size="small">
              <UserAddOutlined />
              注册
            </a-button>
          </a-space>
        </div>
      </div>
    </a-layout-header>
    <a-layout-content class="content">
      <router-view />
    </a-layout-content>
    <a-layout-footer class="footer">Han Picture ©2025 Created with ❤️</a-layout-footer>
  </a-layout>
</template>

<style scoped>
.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  flex: 0 0 auto;
  padding: 0 24px;
  display: flex;
  align-items: center;
  height: 64px;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.logo {
  width: 100px;
  height: 28px;
  margin-right: 32px;
  flex-shrink: 0;
  object-fit: contain;
  cursor: pointer;
}

.nav-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header :deep(.ant-menu) {
  flex: 1;
  border-bottom: none;
}

.user-actions {
  margin-left: 24px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: rgba(0, 0, 0, 0.04);
}

.user-avatar {
  margin-right: 8px;
}

.user-name {
  color: rgba(0, 0, 0, 0.85);
  font-size: 14px;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.content {
  flex: 1 1 auto;
  overflow: auto;
}

.content-body {
  min-height: 280px;
}

.footer {
  flex: 0 0 auto;
  text-align: center;
  background: #f0f2f5;
  padding: 16px 24px;
}
</style>
